import React, { useState, useEffect } from 'react';
import { Form, Input, Select, Button, Space, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import type { ColumnsType } from 'antd/es/table';
import { formatDateTime } from '@/utils/datetime';
import { getStatusTag } from '@/utils/status';
import { submissionService } from '@/services/submissionService';
import { Submission, StatusOption } from '@/types/submission';
import { FilterCard, TableCard } from '@/components/common';
import { RedoOutlined, SearchOutlined, ReloadOutlined, FileSearchOutlined } from '@ant-design/icons';
import { formatMemoryMB } from '@/utils/mappings';

const { Option } = Select;

const SubmissionList: React.FC = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<Submission[]>([]);
  const [statusOptions, setStatusOptions] = useState<StatusOption[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  const columns: ColumnsType<Submission> = [
    {
      title: '提交时间',
      dataIndex: 'create_time',
      render: (time) => formatDateTime(time),
    },
    {
      title: '题目',
      dataIndex: 'problem_title',
      render: (title, record) => (
        <a onClick={() => navigate(`/admin/problem/${record.problem_id}/submit`)}>{title}</a>
      ),
    },
    {
      title: '用户',
      dataIndex: 'username',
    },
    {
      title: '状态',
      dataIndex: 'result',
      render: (result) => getStatusTag(result),
    },
    {
      title: '语言',
      dataIndex: 'language',
    },
    {
      title: '耗时',
      dataIndex: ['statistic_info', 'time_cost'],
      render: (time) => `${time} ms`,
    },
    {
      title: '内存',
      dataIndex: ['statistic_info', 'memory_cost'],
      render: (memory) => formatMemoryMB(memory),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button
          type="link"
          icon={<RedoOutlined />}
          onClick={(e) => {
            e.stopPropagation();
            handleRejudge(record.id);
          }}
        >
          重新评测
        </Button>
      ),
    },
  ];

  const fetchStatusList = async () => {
    try {
      const response = await submissionService.getStatusList();
      setStatusOptions(response.data.data);
    } catch (error) {
      console.error('Failed to fetch status list:', error);
    }
  };

  const fetchSubmissions = async (params = {}) => {
    try {
      setLoading(true);
      const response = await submissionService.getSubmissions({
        ...params,
        page: pagination.current,
        limit: pagination.pageSize,
      });
      const data = response.data.data;
      setData(data.results);
      setPagination(prev => ({ 
        ...prev, 
        total: data.count,
        current: data.current_page,
        pageSize: data.page_size,
      }));
    } catch (error) {
      console.error('Failed to fetch submissions:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchStatusList();
    fetchSubmissionsWithPagination({}, pagination);
  }, []);

  const handleSearch = async (values: any) => {
    const newPagination = { ...pagination, current: 1 };
    setPagination(newPagination);
    await fetchSubmissionsWithPagination(values, newPagination);
  };

  const handleTableChange = (newPagination: any) => {
    setPagination(newPagination);
    // 使用新的分页参数进行查询
    const params = form.getFieldsValue();
    fetchSubmissionsWithPagination(params, newPagination);
  };

  const fetchSubmissionsWithPagination = async (params = {}, newPagination = pagination) => {
    try {
      setLoading(true);
      const response = await submissionService.getSubmissions({
        ...params,
        page: newPagination.current,
        limit: newPagination.pageSize,
      });
      const data = response.data.data;
      setData(data.results);
      setPagination(prev => ({ 
        ...prev, 
        total: data.count,
        current: data.current_page,
        pageSize: data.page_size,
      }));
    } catch (error) {
      console.error('Failed to fetch submissions:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleReset = () => {
    form.resetFields();
    const newPagination = { ...pagination, current: 1 };
    setPagination(newPagination);
    fetchSubmissionsWithPagination({}, newPagination);
  };

  const handleRejudge = async (id: string) => {
    try {
      await submissionService.rejudge(id);
      message.success('已提交重新评测');
      fetchSubmissionsWithPagination(form.getFieldsValue(), pagination);
    } catch (error) {
      message.error('重新评测失败');
    }
  };

  return (
    <div>
      <FilterCard
        pageTitle="提交记录"
        titleIcon={<FileSearchOutlined />}
        form={form}
        onFinish={handleSearch}
        onReset={handleReset}
      >
        <Form.Item name="problem_id" label="题目ID">
          <Input placeholder="请输入题目ID" />
        </Form.Item>
        <Form.Item name="username" label="用户名">
          <Input placeholder="请输入用户名" />
        </Form.Item>
        <Form.Item name="status" label="状态">
          <Select placeholder="请选择状态" allowClear style={{ width: 200 }}>
            {statusOptions.map(option => (
              <Option key={option.value} value={option.value}>
                {option.name}
              </Option>
            ))}
          </Select>
        </Form.Item>
      </FilterCard>

      <TableCard
        tableProps={{
          columns: columns,
          dataSource: data,
          rowKey: 'id',
          pagination: pagination,
          loading: loading,
          onChange: handleTableChange,
          onRow: (record) => ({
            onClick: () => navigate(`/admin/submission/${record.id}`),
          }),
        }}
      />
    </div>
  );
};

export default SubmissionList; 